package com.joelbitar.switchctrl;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class Server {
	private long id;
	private String name;
	private String hosturl;
	private String username;
	private String password;
	private boolean visible; // If to show in the main GUI
	
	/* Public setters */
	public void setId(long id) {
		this.id = id;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setHosturl(String url) {
		this.hosturl = url;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void setVisible(boolean visible) {
		
		this.visible = visible;
	}
	
	/* Public getters */
	// id
	public long getId() {
		return this.id;
	}
	// name
	public String getName() {
		String name = this.name;
		
		if(name == null || name.trim() == ""){
			name = "[unnamed]";
		}
		
		return name;
		
	}
	// visible
	// if should be visible in the main gui
	public boolean getVisible() {
		return this.visible;
	}
	// URL to host
	public String getHosturl() {
		return this.hosturl;
	}
	// username on server
	public String getUsername() {
		return this.username;
	}
	// password on server, as clear text
	public String getPassword() {
		return this.password;
	}
	public String getEncryptedPassword() {
		// TODO Return proper MD5 string
		
		String hashtext = "";
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			
			byte[] digest = md.digest(password.getBytes());
			BigInteger bigInt = new BigInteger(1,digest);
			hashtext = bigInt.toString(16);

			Log.i("MD5", hashtext);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return hashtext;
	}
	
	public void setFromCursor(Cursor cursor) {
		this.setId(cursor.getInt(ServerDbAdapter.ID_COLUMN));
		this.setHosturl(cursor.getString(ServerDbAdapter.URL_COLUMN));
		this.setUsername(cursor.getString(ServerDbAdapter.USERNAME_COLUMN));
		this.setPassword(cursor.getString(ServerDbAdapter.PASSWORD_COLUMN));
		this.setName(cursor.getString(ServerDbAdapter.NAME_COLUMN));
		int b = cursor.getInt(ServerDbAdapter.SHOW_COLUMN);
		
		boolean visible = false;
		if(b == 1)
		{
			visible = true;
		}
		
		Log.i("visible", "v: " + b);
		
		if(visible)
		{
			Log.i("visible", "YEAH! is visible: " + b);
		}
		else
		{
			Log.i("visible", "buhu, is not visible: " + b);
		}
		
		
		this.setVisible(visible);
	}
	
}
